"""
空间占用检测服务
实现教室、办公室等空间的占用检测，创建空间使用率的统计和分析，开发空闲空间的节能提醒功能
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
import json
from enum import Enum

logger = logging.getLogger(__name__)


class OccupancyStatus(str, Enum):
    """占用状态枚举"""
    OCCUPIED = "occupied"      # 占用
    VACANT = "vacant"          # 空闲
    PARTIALLY_OCCUPIED = "partially_occupied"  # 部分占用
    UNKNOWN = "unknown"        # 未知


class SpaceType(str, Enum):
    """空间类型枚举"""
    CLASSROOM = "classroom"    # 教室
    OFFICE = "office"         # 办公室
    MEETING_ROOM = "meeting_room"  # 会议室
    LIBRARY = "library"       # 图书馆
    LABORATORY = "laboratory"  # 实验室
    CAFETERIA = "cafeteria"   # 食堂
    AUDITORIUM = "auditorium" # 礼堂
    CORRIDOR = "corridor"     # 走廊


class EnergyRecommendationType(str, Enum):
    """节能建议类型枚举"""
    LIGHTING_OFF = "lighting_off"           # 关闭照明
    HVAC_ADJUST = "hvac_adjust"            # 调整空调
    EQUIPMENT_STANDBY = "equipment_standby" # 设备待机
    VENTILATION_REDUCE = "ventilation_reduce" # 减少通风
    GENERAL_ENERGY_SAVE = "general_energy_save" # 一般节能


class SpaceOccupancyResult:
    """空间占用检测结果"""
    def __init__(self, detection_id: str, camera_id: str, space_id: str,
                 timestamp: datetime, occupancy_status: OccupancyStatus,
                 occupancy_rate: float, person_count: int, capacity: int,
                 space_type: SpaceType, confidence: float,
                 detected_activities: List[Dict[str, Any]],
                 energy_recommendations: List[Dict[str, Any]],
                 usage_duration: Optional[int] = None):
        self.detection_id = detection_id
        self.camera_id = camera_id
        self.space_id = space_id
        self.timestamp = timestamp
        self.occupancy_status = occupancy_status
        self.occupancy_rate = occupancy_rate
        self.person_count = person_count
        self.capacity = capacity
        self.space_type = space_type
        self.confidence = confidence
        self.detected_activities = detected_activities
        self.energy_recommendations = energy_recommendations
        self.usage_duration = usage_duration


class SpaceConfig:
    """空间配置"""
    def __init__(self, space_id: str, space_name: str, space_type: SpaceType,
                 capacity: int, area_sqm: float, operating_hours: Dict[str, Tuple[str, str]],
                 energy_saving_enabled: bool = True,
                 occupancy_threshold: float = 0.1,
                 vacancy_timeout_minutes: int = 30):
        self.space_id = space_id
        self.space_name = space_name
        self.space_type = space_type
        self.capacity = capacity
        self.area_sqm = area_sqm
        self.operating_hours = operating_hours
        self.energy_saving_enabled = energy_saving_enabled
        self.occupancy_threshold = occupancy_threshold
        self.vacancy_timeout_minutes = vacancy_timeout_minutes


class OccupancyDetector:
    """占用检测器"""
    
    def __init__(self):
        self.person_detection_threshold = 0.5
        self.movement_detection_threshold = 30
        self.furniture_detection_enabled = True
    
    def detect_persons(self, image: np.ndarray) -> List[Dict[str, Any]]:
        """检测人员"""
        # 模拟人员检测（实际应用中会使用YOLO等模型）
        height, width = image.shape[:2]
        
        # 简化的人员检测：基于图像亮度和运动检测
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
        
        # 使用简单的阈值检测模拟人员检测
        # 在实际应用中，这里会调用人员检测模型
        persons = []
        
        # 模拟检测结果
        avg_brightness = np.mean(gray)
        if avg_brightness > 100:  # 如果图像较亮，可能有人员活动
            # 随机生成1-5个人员检测结果
            num_persons = np.random.randint(0, 6)
            
            for i in range(num_persons):
                person = {
                    'person_id': f"person_{i}",
                    'bbox': [
                        np.random.randint(0, width//2),
                        np.random.randint(0, height//2),
                        np.random.randint(width//2, width),
                        np.random.randint(height//2, height)
                    ],
                    'confidence': np.random.uniform(0.6, 0.95),
                    'activity': np.random.choice(['sitting', 'standing', 'walking', 'working'])
                }
                persons.append(person)
        
        return persons
    
    def detect_furniture_usage(self, image: np.ndarray, persons: List[Dict[str, Any]]) -> Dict[str, Any]:
        """检测家具使用情况"""
        if not self.furniture_detection_enabled:
            return {'chairs_occupied': 0, 'desks_occupied': 0, 'total_furniture': 0}
        
        # 模拟家具使用检测
        chairs_occupied = len([p for p in persons if p.get('activity') == 'sitting'])
        desks_occupied = len([p for p in persons if p.get('activity') in ['sitting', 'working']])
        
        # 估算总家具数量（基于空间类型）
        total_furniture = max(chairs_occupied + 2, 10)  # 至少10个座位
        
        return {
            'chairs_occupied': chairs_occupied,
            'desks_occupied': desks_occupied,
            'total_furniture': total_furniture,
            'furniture_utilization': chairs_occupied / total_furniture if total_furniture > 0 else 0
        }
    
    def analyze_activities(self, persons: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """分析活动"""
        activities = []
        
        activity_counts = defaultdict(int)
        for person in persons:
            activity = person.get('activity', 'unknown')
            activity_counts[activity] += 1
        
        for activity, count in activity_counts.items():
            activities.append({
                'activity_type': activity,
                'person_count': count,
                'confidence': 0.8
            })
        
        return activities
    
    def calculate_occupancy_rate(self, person_count: int, capacity: int) -> float:
        """计算占用率"""
        if capacity <= 0:
            return 0.0
        return min(1.0, person_count / capacity)
    
    def determine_occupancy_status(self, occupancy_rate: float, threshold: float = 0.1) -> OccupancyStatus:
        """确定占用状态"""
        if occupancy_rate == 0:
            return OccupancyStatus.VACANT
        elif occupancy_rate < threshold:
            return OccupancyStatus.VACANT
        elif occupancy_rate < 0.7:
            return OccupancyStatus.PARTIALLY_OCCUPIED
        else:
            return OccupancyStatus.OCCUPIED


class EnergyRecommendationEngine:
    """节能建议引擎"""
    
    def __init__(self):
        self.recommendation_rules = {
            'vacant_space': {
                'lighting': 'turn_off_after_15min',
                'hvac': 'reduce_to_minimum',
                'equipment': 'standby_mode'
            },
            'partially_occupied': {
                'lighting': 'zone_control',
                'hvac': 'adjust_to_occupied_areas',
                'equipment': 'selective_operation'
            },
            'occupied': {
                'lighting': 'maintain_optimal',
                'hvac': 'maintain_comfort',
                'equipment': 'full_operation'
            }
        }
    
    def generate_recommendations(self, occupancy_result: SpaceOccupancyResult,
                               space_config: SpaceConfig) -> List[Dict[str, Any]]:
        """生成节能建议"""
        recommendations = []
        
        if not space_config.energy_saving_enabled:
            return recommendations
        
        current_time = occupancy_result.timestamp
        weekday = current_time.strftime('%A').lower()
        
        # 检查是否在工作时间
        is_operating_hours = self._is_operating_hours(current_time, space_config.operating_hours, weekday)
        
        # 基于占用状态生成建议
        if occupancy_result.occupancy_status == OccupancyStatus.VACANT:
            if not is_operating_hours:
                recommendations.append({
                    'type': EnergyRecommendationType.LIGHTING_OFF.value,
                    'priority': 'high',
                    'description': '非工作时间且空间空闲，建议关闭照明',
                    'estimated_savings': '80%',
                    'action': 'turn_off_lighting'
                })
                
                recommendations.append({
                    'type': EnergyRecommendationType.HVAC_ADJUST.value,
                    'priority': 'high',
                    'description': '非工作时间且空间空闲，建议调整空调至节能模式',
                    'estimated_savings': '60%',
                    'action': 'set_hvac_eco_mode'
                })
            else:
                # 工作时间但空闲
                recommendations.append({
                    'type': EnergyRecommendationType.LIGHTING_OFF.value,
                    'priority': 'medium',
                    'description': f'空间已空闲超过{space_config.vacancy_timeout_minutes}分钟，建议关闭部分照明',
                    'estimated_savings': '40%',
                    'action': 'reduce_lighting'
                })
        
        elif occupancy_result.occupancy_status == OccupancyStatus.PARTIALLY_OCCUPIED:
            if occupancy_result.occupancy_rate < 0.3:
                recommendations.append({
                    'type': EnergyRecommendationType.LIGHTING_OFF.value,
                    'priority': 'medium',
                    'description': '空间利用率较低，建议实施分区照明控制',
                    'estimated_savings': '25%',
                    'action': 'zone_lighting_control'
                })
                
                recommendations.append({
                    'type': EnergyRecommendationType.HVAC_ADJUST.value,
                    'priority': 'medium',
                    'description': '空间利用率较低，建议调整空调至部分区域',
                    'estimated_savings': '30%',
                    'action': 'zone_hvac_control'
                })
        
        # 基于空间类型的特殊建议
        if space_config.space_type == SpaceType.CLASSROOM:
            if occupancy_result.occupancy_status == OccupancyStatus.VACANT and is_operating_hours:
                recommendations.append({
                    'type': EnergyRecommendationType.EQUIPMENT_STANDBY.value,
                    'priority': 'low',
                    'description': '教室空闲，建议将投影仪等设备切换至待机模式',
                    'estimated_savings': '15%',
                    'action': 'equipment_standby'
                })
        
        elif space_config.space_type == SpaceType.OFFICE:
            if occupancy_result.occupancy_status == OccupancyStatus.VACANT:
                recommendations.append({
                    'type': EnergyRecommendationType.EQUIPMENT_STANDBY.value,
                    'priority': 'medium',
                    'description': '办公室空闲，建议关闭电脑显示器和非必要设备',
                    'estimated_savings': '20%',
                    'action': 'office_equipment_standby'
                })
        
        return recommendations
    
    def _is_operating_hours(self, current_time: datetime, 
                          operating_hours: Dict[str, Tuple[str, str]], 
                          weekday: str) -> bool:
        """检查是否在工作时间"""
        if weekday not in operating_hours:
            return False
        
        start_time_str, end_time_str = operating_hours[weekday]
        
        try:
            start_hour, start_minute = map(int, start_time_str.split(':'))
            end_hour, end_minute = map(int, end_time_str.split(':'))
            
            current_hour = current_time.hour
            current_minute = current_time.minute
            
            start_minutes = start_hour * 60 + start_minute
            end_minutes = end_hour * 60 + end_minute
            current_minutes = current_hour * 60 + current_minute
            
            return start_minutes <= current_minutes <= end_minutes
        except:
            return True  # 如果解析失败，默认为工作时间

class SpaceOccupancyService:
    """空间占用检测服务"""
    
    def __init__(self):
        self.detector = OccupancyDetector()
        self.recommendation_engine = EnergyRecommendationEngine()
        
        self.detection_results: List[SpaceOccupancyResult] = []
        self.space_configs: Dict[str, SpaceConfig] = {}
        self.occupancy_history: Dict[str, deque] = defaultdict(lambda: deque(maxlen=100))
        
        # 服务状态
        self._running = False
        self._monitoring_task = None
        self.monitoring_interval = 60.0  # 1分钟检查一次
        
        # 初始化默认配置
        self._initialize_default_configs()
        
        # 统计信息
        self.stats = {
            'total_detections': 0,
            'spaces_monitored': 0,
            'average_occupancy_rate': 0.0,
            'energy_recommendations_generated': 0,
            'vacant_spaces_count': 0,
            'occupied_spaces_count': 0
        }
    
    def _initialize_default_configs(self):
        """初始化默认空间配置"""
        # 教室配置
        classroom_config = SpaceConfig(
            space_id="classroom_default",
            space_name="默认教室",
            space_type=SpaceType.CLASSROOM,
            capacity=40,
            area_sqm=60.0,
            operating_hours={
                'monday': ('08:00', '18:00'),
                'tuesday': ('08:00', '18:00'),
                'wednesday': ('08:00', '18:00'),
                'thursday': ('08:00', '18:00'),
                'friday': ('08:00', '18:00'),
                'saturday': ('09:00', '17:00'),
                'sunday': ('09:00', '17:00')
            },
            energy_saving_enabled=True,
            occupancy_threshold=0.1,
            vacancy_timeout_minutes=15
        )
        
        # 办公室配置
        office_config = SpaceConfig(
            space_id="office_default",
            space_name="默认办公室",
            space_type=SpaceType.OFFICE,
            capacity=20,
            area_sqm=40.0,
            operating_hours={
                'monday': ('09:00', '18:00'),
                'tuesday': ('09:00', '18:00'),
                'wednesday': ('09:00', '18:00'),
                'thursday': ('09:00', '18:00'),
                'friday': ('09:00', '18:00'),
                'saturday': ('10:00', '16:00'),
                'sunday': ('10:00', '16:00')
            },
            energy_saving_enabled=True,
            occupancy_threshold=0.05,
            vacancy_timeout_minutes=30
        )
        
        # 会议室配置
        meeting_room_config = SpaceConfig(
            space_id="meeting_room_default",
            space_name="默认会议室",
            space_type=SpaceType.MEETING_ROOM,
            capacity=12,
            area_sqm=25.0,
            operating_hours={
                'monday': ('08:00', '20:00'),
                'tuesday': ('08:00', '20:00'),
                'wednesday': ('08:00', '20:00'),
                'thursday': ('08:00', '20:00'),
                'friday': ('08:00', '20:00'),
                'saturday': ('09:00', '18:00'),
                'sunday': ('09:00', '18:00')
            },
            energy_saving_enabled=True,
            occupancy_threshold=0.08,
            vacancy_timeout_minutes=10
        )
        
        self.space_configs = {
            "classroom": classroom_config,
            "office": office_config,
            "meeting_room": meeting_room_config
        }
    
    async def start_service(self):
        """启动服务"""
        if self._running:
            return
        
        self._running = True
        self._monitoring_task = asyncio.create_task(self._monitoring_loop())
        logger.info("Space occupancy service started")
    
    async def stop_service(self):
        """停止服务"""
        self._running = False
        if self._monitoring_task:
            self._monitoring_task.cancel()
            try:
                await self._monitoring_task
            except asyncio.CancelledError:
                pass
        logger.info("Space occupancy service stopped")
    
    async def _monitoring_loop(self):
        """监控循环"""
        while self._running:
            try:
                await self._periodic_monitoring()
                await asyncio.sleep(self.monitoring_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in space occupancy monitoring loop: {e}")
                await asyncio.sleep(30.0)
    
    async def _periodic_monitoring(self):
        """周期性监控"""
        # 清理过期数据
        cutoff_time = datetime.now() - timedelta(days=7)
        
        self.detection_results = [
            result for result in self.detection_results
            if result.timestamp > cutoff_time
        ]
        
        # 更新统计信息
        self._update_statistics()
        
        # 检查长时间空闲的空间
        await self._check_vacant_spaces()
    
    def _update_statistics(self):
        """更新统计信息"""
        if not self.detection_results:
            return
        
        self.stats['total_detections'] = len(self.detection_results)
        self.stats['spaces_monitored'] = len(set(r.space_id for r in self.detection_results))
        
        # 计算平均占用率
        occupancy_rates = [r.occupancy_rate for r in self.detection_results]
        self.stats['average_occupancy_rate'] = np.mean(occupancy_rates)
        
        # 统计空间状态
        recent_results = [r for r in self.detection_results if 
                         (datetime.now() - r.timestamp).total_seconds() < 3600]  # 最近1小时
        
        vacant_count = len([r for r in recent_results if r.occupancy_status == OccupancyStatus.VACANT])
        occupied_count = len([r for r in recent_results if r.occupancy_status == OccupancyStatus.OCCUPIED])
        
        self.stats['vacant_spaces_count'] = vacant_count
        self.stats['occupied_spaces_count'] = occupied_count
        
        # 统计节能建议
        recommendations_count = sum(len(r.energy_recommendations) for r in self.detection_results)
        self.stats['energy_recommendations_generated'] = recommendations_count
    
    async def _check_vacant_spaces(self):
        """检查长时间空闲的空间"""
        current_time = datetime.now()
        
        for space_id, history in self.occupancy_history.items():
            if len(history) < 3:  # 数据不足
                continue
            
            # 检查最近3次检测是否都是空闲状态
            recent_vacant = all(
                result.occupancy_status == OccupancyStatus.VACANT 
                for result in list(history)[-3:]
            )
            
            if recent_vacant:
                space_config = self._get_space_config(space_id)
                if space_config and space_config.energy_saving_enabled:
                    logger.info(f"Space {space_id} has been vacant for extended period")
    
    async def detect_space_occupancy(self, image: np.ndarray, camera_id: str,
                                   space_id: str) -> SpaceOccupancyResult:
        """检测空间占用状态"""
        try:
            detection_id = str(uuid4())
            timestamp = datetime.now()
            
            # 获取空间配置
            space_config = self._get_space_config(space_id)
            if not space_config:
                raise ValueError(f"Space configuration not found for {space_id}")
            
            # 检测人员
            persons = self.detector.detect_persons(image)
            person_count = len(persons)
            
            # 计算占用率
            occupancy_rate = self.detector.calculate_occupancy_rate(person_count, space_config.capacity)
            
            # 确定占用状态
            occupancy_status = self.detector.determine_occupancy_status(
                occupancy_rate, space_config.occupancy_threshold
            )
            
            # 分析活动
            detected_activities = self.detector.analyze_activities(persons)
            
            # 检测家具使用情况
            furniture_usage = self.detector.detect_furniture_usage(image, persons)
            detected_activities.append({
                'activity_type': 'furniture_usage',
                'details': furniture_usage,
                'confidence': 0.9
            })
            
            # 计算使用持续时间
            usage_duration = self._calculate_usage_duration(space_id, occupancy_status)
            
            # 计算置信度
            confidence = self._calculate_confidence(person_count, occupancy_rate, len(detected_activities))
            
            # 创建检测结果
            result = SpaceOccupancyResult(
                detection_id=detection_id,
                camera_id=camera_id,
                space_id=space_id,
                timestamp=timestamp,
                occupancy_status=occupancy_status,
                occupancy_rate=occupancy_rate,
                person_count=person_count,
                capacity=space_config.capacity,
                space_type=space_config.space_type,
                confidence=confidence,
                detected_activities=detected_activities,
                energy_recommendations=[],  # 将在下面填充
                usage_duration=usage_duration
            )
            
            # 生成节能建议
            energy_recommendations = self.recommendation_engine.generate_recommendations(result, space_config)
            result.energy_recommendations = energy_recommendations
            
            # 存储结果
            self.detection_results.append(result)
            self.occupancy_history[space_id].append(result)
            
            # 保持最近1000个检测结果
            if len(self.detection_results) > 1000:
                self.detection_results = self.detection_results[-1000:]
            
            logger.info(f"Space occupancy detected for {space_id}: {occupancy_status.value}, rate {occupancy_rate:.2f}")
            
            return result
            
        except Exception as e:
            logger.error(f"Failed to detect space occupancy: {e}")
            raise
    
    def _get_space_config(self, space_id: str) -> Optional[SpaceConfig]:
        """获取空间配置"""
        # 尝试精确匹配
        if space_id in self.space_configs:
            return self.space_configs[space_id]
        
        # 基于空间类型匹配
        if 'classroom' in space_id.lower():
            return self.space_configs['classroom']
        elif 'office' in space_id.lower():
            return self.space_configs['office']
        elif 'meeting' in space_id.lower():
            return self.space_configs['meeting_room']
        else:
            # 返回默认配置
            return self.space_configs['classroom']
    
    def _calculate_usage_duration(self, space_id: str, current_status: OccupancyStatus) -> Optional[int]:
        """计算使用持续时间"""
        history = self.occupancy_history.get(space_id, deque())
        
        if len(history) < 2:
            return None
        
        # 查找状态变化点
        duration_minutes = 0
        for i in range(len(history) - 1, 0, -1):
            if history[i].occupancy_status == current_status:
                time_diff = (history[i].timestamp - history[i-1].timestamp).total_seconds() / 60
                duration_minutes += time_diff
            else:
                break
        
        return int(duration_minutes) if duration_minutes > 0 else None
    
    def _calculate_confidence(self, person_count: int, occupancy_rate: float, activity_count: int) -> float:
        """计算检测置信度"""
        confidence = 0.5  # 基础置信度
        
        # 基于人员数量的置信度
        if person_count > 0:
            confidence += 0.3
        
        # 基于占用率的置信度
        if occupancy_rate > 0.1:
            confidence += 0.1
        
        # 基于活动检测的置信度
        if activity_count > 0:
            confidence += 0.1
        
        return min(1.0, confidence)
    
    async def get_detection_results(self, space_id: Optional[str] = None,
                                  start_time: Optional[datetime] = None,
                                  end_time: Optional[datetime] = None,
                                  limit: int = 100) -> List[SpaceOccupancyResult]:
        """获取检测结果"""
        results = self.detection_results
        
        # 过滤条件
        if space_id:
            results = [r for r in results if r.space_id == space_id]
        
        if start_time:
            results = [r for r in results if r.timestamp >= start_time]
        
        if end_time:
            results = [r for r in results if r.timestamp <= end_time]
        
        # 按时间倒序排列
        results.sort(key=lambda x: x.timestamp, reverse=True)
        
        return results[:limit]
    
    async def get_space_usage_stats(self, space_id: str, days: int = 7) -> Dict[str, Any]:
        """获取空间使用统计"""
        end_time = datetime.now()
        start_time = end_time - timedelta(days=days)
        
        # 获取时间范围内的检测结果
        space_results = [
            r for r in self.detection_results
            if r.space_id == space_id and start_time <= r.timestamp <= end_time
        ]
        
        if not space_results:
            return {
                'space_id': space_id,
                'total_detections': 0,
                'average_occupancy_rate': 0.0,
                'peak_occupancy': 0.0,
                'utilization_hours': 0.0,
                'energy_savings_potential': 0.0
            }
        
        # 计算统计指标
        total_detections = len(space_results)
        occupancy_rates = [r.occupancy_rate for r in space_results]
        average_occupancy_rate = np.mean(occupancy_rates)
        peak_occupancy = np.max(occupancy_rates)
        
        # 计算利用时间
        occupied_results = [r for r in space_results if r.occupancy_status != OccupancyStatus.VACANT]
        utilization_hours = len(occupied_results) * (self.monitoring_interval / 60)  # 转换为小时
        
        # 计算节能潜力
        vacant_results = [r for r in space_results if r.occupancy_status == OccupancyStatus.VACANT]
        energy_savings_potential = len(vacant_results) / total_detections * 100
        
        # 状态分布
        status_distribution = defaultdict(int)
        for result in space_results:
            status_distribution[result.occupancy_status.value] += 1
        
        return {
            'space_id': space_id,
            'total_detections': total_detections,
            'average_occupancy_rate': average_occupancy_rate,
            'peak_occupancy': peak_occupancy,
            'utilization_hours': utilization_hours,
            'energy_savings_potential': energy_savings_potential,
            'status_distribution': dict(status_distribution),
            'period_days': days
        }
    
    def add_space_config(self, config: SpaceConfig):
        """添加空间配置"""
        self.space_configs[config.space_id] = config
        logger.info(f"Added space config: {config.space_id}")
    
    def get_space_configs(self) -> List[SpaceConfig]:
        """获取所有空间配置"""
        return list(self.space_configs.values())
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.stats.copy()
    
    async def get_energy_recommendations(self, space_id: Optional[str] = None,
                                       hours: int = 24) -> List[Dict[str, Any]]:
        """获取节能建议"""
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=hours)
        
        results = await self.get_detection_results(
            space_id=space_id,
            start_time=start_time,
            end_time=end_time
        )
        
        # 收集所有节能建议
        all_recommendations = []
        for result in results:
            for rec in result.energy_recommendations:
                rec['space_id'] = result.space_id
                rec['timestamp'] = result.timestamp
                all_recommendations.append(rec)
        
        # 按优先级和时间排序
        priority_order = {'high': 3, 'medium': 2, 'low': 1}
        all_recommendations.sort(
            key=lambda x: (priority_order.get(x.get('priority', 'low'), 1), x.get('timestamp', datetime.min)),
            reverse=True
        )
        
        return all_recommendations


# 全局空间占用检测服务实例
space_occupancy_service = SpaceOccupancyService()